import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Connection, IsNull, Repository } from 'typeorm'
import { Role } from '../entity/Role'
import { BusinessException } from 'src/common/exceptions/business.exception'
import { UserInfoService } from 'src/user-info/user-info.service'
import { UserInfo } from 'src/entity/Userinfo'
@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private roleRepository: Repository<Role>,
    private readonly userInfoService: UserInfoService,
    private connection: Connection,
  ) { }

  // 添加角色
  async add(data: {
    roleName: string
    roleCode: string
    validFlag: boolean
    remark: string
    sortOrder: number
  }) {
    const find = await this.roleRepository.findOne({
      where: {
        roleName: data.roleName,
      },
    })
    if (find) return new BusinessException('角色编码已存在')
    return await this.roleRepository.save(data)
  }

  // 设置权限
  async setRolePermission(data: {
    roleId: {
      id: number
    }
    funcIds: {
      id: number
    }[]
  }) {
    const ids = data.funcIds.map((item) => {
      return item.id
    })
    let idsStr
    if (ids.length !== 0) {
      idsStr = ids.join(',')
    } else {
      idsStr = null
    }
    await this.roleRepository.update(
      {
        id: data.roleId.id,
      },
      {
        menuIds: idsStr,
      },
    )
  }

  // 通过角色编号来查询拥有的菜单id数组
  async getMenuBYRoleCode(roleCode: string) {
    const roleSqlData = await this.roleRepository.findOne({
      where: {
        roleCode,
      },
    })
    return (
      roleSqlData.menuIds?.split(',').map((item) => {
        return parseInt(item)
      }) || []
    )
  }

  // 为用户添加角色
  async addUser(data: { userId: number; roleIds?: { id: number }[] }) {
    if (data.roleIds.length > 0) {
      const roleSqlDataList = await this.roleRepository.find({
        where: data.roleIds.map((item) => {
          return {
            id: item.id,
          }
        }),
      })
      const roleCodes = []
      const roleNames = []
      roleSqlDataList.forEach((item) => {
        roleCodes.push(item.roleCode)
        roleNames.push(item.roleName)
      })
      const roleCodesStr = roleCodes.length ? roleCodes.join(',') : null
      const roleNamesStr = roleNames.length ? roleNames.join(',') : null
      return await this.userInfoService.update({
        userId: data.userId,
        property: ['roleCode', 'roleName'],
        propertyValue: [roleCodesStr, roleNamesStr],
      })
    } else {
      return await this.userInfoService.update({
        userId: data.userId,
        property: ['roleCode', 'roleName'],
        propertyValue: [null, null],
      })
    }
    // userInfoSqlData.
  }

  // 通过角色编码为用户添加角色
  async addUserByCode(data: { userId: number; roleCode: string }) {
    console.log('userId', data, data.userId, data.roleCode)

    await this.connection.transaction(async (manager) => {
      const roleSqlData = await manager.findOne(Role, {
        where: {
          roleCode: data.roleCode,
          isDelete: IsNull(),
        },
      })
      if (roleSqlData) {
        await manager.update(
          UserInfo,
          {
            userId: data.userId,
          },
          {
            roleCode: data.roleCode,
            roleName: roleSqlData.roleName,
          },
        )
      } else {
        throw new BusinessException('角色编码不存在')
      }
    })
    return {}
  }

  // 获取所有角色
  async getAllRole(data: any) {
    const roleSqlData = await this.roleRepository.find({
      where: {
        isDelete: IsNull(),
      },
    })
    return roleSqlData.map((item) => {
      return {
        label: item.roleName,
        value: item.roleCode,
      }
    })
  }

  // 分页查询
  async getPageList({ pageRequest: { pageIndex, pageSize }, orgId }) {
    const sqlAllData = await this.roleRepository.find({
      where: {
        isDelete: IsNull(),
      },
    })
    const sqlData = await this.roleRepository.find({
      where: {
        isDelete: IsNull(),
      },
      order: {
        sortOrder: 'ASC',
      },
      skip: (pageIndex - 1) * pageSize,
      take: pageSize,
      withDeleted: false,
    })

    return {
      content: sqlData.map((item) => {
        return {
          ...item,
          menuIds: item.menuIds?.split(',') || [],
        }
      }),
      total: sqlAllData.length,
    }
  }

  // 修改角色
  async update(data) {
    if (!data.validFlag) data.validFlag = false
    if (!data.isDelete) delete data.isDelete
    if (!data.menuIds.length) delete data.menuIds
    if (data.menuIds.length) {
      data.menuIds = data.menuIds.join(',')
    }
    await this.roleRepository.update(
      {
        id: data.id,
      },
      data,
    )
  }

  // 删除角色
  async del(data) {
    this.roleRepository.update(
      {
        id: data.id,
      },
      {
        isDelete: true,
      },
    )
  }

  // 为角色设置菜单权限
  async setMenuByRole(data) { }
}
